package com.example.test15middleware.common;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: fxy
 * @Date: 2022/05/30/14:45
 * @Description:
 */
@Component
public class RedisUtil {
        @Resource
        private RedissonClient redissonClient;

        @Resource
        public RedisTemplate<String,Object> redisTemplate;


        /**
         * 加锁
         *
         * @param lockKey
         * @return
         */
        public RLock lock(String lockKey) {
            RLock lock = redissonClient.getLock(lockKey);
            lock.lock();
            return lock;
        }

        /**
         * 释放锁
         *
         * @param lockKey
         */
        public void unlock(String lockKey) {
            RLock lock = redissonClient.getLock(lockKey);
            lock.unlock();
        }

        /**
         * 释放锁
         *
         * @param lock
         */
        public static void unlock(RLock lock) {
            lock.unlock();
        }

        /**
         * 带超时的锁
         *
         * @param lockKey
         * @param timeoutSeconds 超时时间   单位：秒
         */
        public RLock lock(String lockKey, int timeoutSeconds) {
            RLock lock = redissonClient.getLock(lockKey);
            lock.lock(timeoutSeconds, TimeUnit.SECONDS);
            return lock;
        }

        /**
         * 带超时的锁
         *
         * @param lockKey
         * @param unit    时间单位
         * @param timeout 超时时间
         */
        public RLock lock(String lockKey, TimeUnit unit, int timeout) {
            RLock lock = redissonClient.getLock(lockKey);
            lock.lock(timeout, unit);
            return lock;
        }

        /**
         * 尝试获取锁
         *
         * @param lockKey
         * @param waitTimeSeconds  最多等待时间
         * @param leaseTimeSeconds 上锁后自动释放锁时间
         */
        public boolean tryLock(String lockKey, int waitTimeSeconds, int leaseTimeSeconds) {
            RLock lock = redissonClient.getLock(lockKey);
            try {
                return lock.tryLock(waitTimeSeconds, leaseTimeSeconds, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                return false;
            }
        }

        /**
         * 尝试获取锁
         *
         * @param lockKey
         * @param unit      时间单位
         * @param waitTime  最多等待时间
         * @param leaseTime 上锁后自动释放锁时间
         */
        public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
            RLock lock = redissonClient.getLock(lockKey);
            try {
                return lock.tryLock(waitTime, leaseTime, unit);
            } catch (InterruptedException e) {
                return false;
            }
        }
}
